#!/bin/sh
#============Header=================================================|
#AUTHOR
# Jefferson Rocha <lrcjefferson@gmail.com>
#
#PROGRAM
# UPWIFI - FOR SLACKWARE
#===================================================================|

#=====VARIABLES===================|
# Your interface, example wlan0.
# Sua interface exemplo wlan0.
interface=""

# Your network
# Use command iwlist
# Sua rede
# Use o comando iwlist
network=""

# Your Password
# Seu password da rede
password=""

# wpa-supplicant.conf
supplicant="/etc/wpa_supplicant.conf"

#=====TESTS=======================|
# Root?
[ "$UID" -ne "0" ] && { echo "Only Root."; exit 1;}

# Vars null?
for conf in "$interface" "$network" "$password"; do
   if [ -z "$conf" ]; then
      printf '%b\n' "\e[31;1mERROR, VARIABLE NULL IN SOURCE PROGRAM.\e[m"
      printf '%s\n' "USE ' upwifi help ' FOR HELP"
      exit 1
   fi
done

#=====FUNCTIONS==================|
_start(){ # Function Only UP WIFI
# Up wireless interface
if ifconfig "${interface}" up; then
   printf '%b\n' "\e[32;1mINTERFACE ${interface} UP...[OK]\e[m"
fi

if wpa_supplicant -i "$interface" -c "supplicant" -B -D wext; then
  printf '%b\n' "\e[32;1mDaemon Mode...[OK]\e[m"
else
  printf '%b\n' "\e[31;1mDaemon Mode ERROR!\e[m"
  exit 1
fi

# UP WIFI
if dhclient "$interface"; then
   printf '%b\n' "\e[32;1mdhclient...[OK]\e[m"
else
   printf '%b\n' "\e[32;1mdhclient ERROR...[X]"
   exit 1
fi
}

_create(){ # Function Create all conf for run WIFI
# Up wireless interface
if ifconfig "${interface}" up; then
   printf '%b\n' "\e[32;1mINTERFACE ${interface} UP...[OK]\e[m"
else
   printf '%b\n' "\e[31;1mINTERFACE ${interface} NO UP...[X]"
   exit 1
fi

if wpa_passphrase "$network" "$password" > "$supplicant"; then
   printf '%b\n' "\e[32;1m${supplicant} CREATED...[OK]\e[m"
else
   printf '%b\n' "\e[31;1m${supplicant} NOT CREATED...[X]\e[m"
   exit 1
fi
}

_usage(){
clear
cat <<END
upwifi [OPTIONS]
Manual USAGE.

OPTIONS IN LINE:
-----------------------------------------------------
 start
      Your conf file created? ok, now run upwifi:
      # upwifi start
-----------------------------------------------------
 create
      For Create a new configuration use:
      # upwifi create
      Do not forget to fill in all variables present 
      internally in the program ...

      !! FILL ALL THE FIELDS !!
      interface="INTERFACE HERE"
      network="NETWORK HERE"
      password="PASSWORD HERE"
-----------------------------------------------------
END
}


############
#START     #
############

# Call functions
case "$1" in
   start)  _start  ;;
   create) _create ;;
   help)   _usage  ;;
   *) _usage       ;;
esac
